<template>
  <el-dialog
    class="assign-role"
    title="分配角色"
    :visible="showRoleDialog"
    @close="closeRoleDialog"
    @open="openRoleDialog"
  >
    <!-- 这里准备复选框 -->

    <el-checkbox-group v-model="roleIds" v-loading="loading">
      <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button type="primary" size="small" @click="submit">确定</el-button>
      <el-button size="small" @click="closeRoleDialog">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { reqGetRoleList } from '@/api/setting'
import { reqGetUserDetaIlById } from '@/api/user'
import { reqAssignRoles } from '@/api/employees'
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      // 多选框的数组
      roleIds: [],
      // 渲染数据的数组
      roleList: []
    }
  },
  async created() {
    // const { data: { rows }} = await reqGetRoleList(1, 100)
    // console.log(rows)
    // this.roleList = rows
  },
  methods: {
    // 点击确认 添加角色
    async submit() {
      await reqAssignRoles({
        id: this.userId,
        roleIds: this.roleIds
      })
      this.$message.success('分配解决成功')
      this.closeRoleDialog()
    },
    // 打开弹框
    async openRoleDialog() {
    //   this.getRloeList()
    //   this.getUserRoles()
      // 希望的需求，不是一个好了再等另一个 是一起发，等全部结果拿到后再把loading状态改成false
      // Promise.all Promise本身的方法(静态方法)非实例
      // 参数是 数组
      // 数组里的每一项是promise
      // 举例 Promise.all([promise1, promise2, promise3, ...]).then(res => {})
      this.loading = true
      await Promise.all([this.getRloeList(), this.getUserRoles()])
      this.loading = false
    },
    // 获取员工id 用来数据回显
    async getUserRoles() {
      const { data: { roleIds }} = await reqGetUserDetaIlById(this.userId)
      console.log('用来回显数据', roleIds)
      this.roleIds = roleIds
    },
    async getRloeList() {
      const { data: { rows }} = await reqGetRoleList(1, 100)
      console.log(rows)
      console.log(this.userId)
      this.roleList = rows
    },
    closeRoleDialog() {
      this.$emit('update:showRoleDialog', false)
    }
  }
}
</script>
